# -*- coding: utf-8 -*-
from django.db import models
from django.contrib import admin
from pygameweb import markup
from django.contrib.auth.models import User

import datetime

#from utils.fields import AutoUniqueSlugField
    
class NewsManager(models.Manager):
    def get_query_set(self):
        return super(NewsManager, self).get_query_set()\
                .filter(active=True).order_by("-created")


class News(models.Model):
    """
    a news model
    
    :todo: icon for news? -> icon field?
    """
    # basic fields
    title = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(unique=True)
    # markup options, including raw html    
    markup = models.CharField(max_length=5, choices=markup.ADMIN_CHOICES)

    content = models.TextField()
    # raw html from rendered markup for caching
    raw_content = models.TextField(editable=False)

    active =  models.BooleanField(default=True)

    created = models.DateTimeField(null=True, editable=False)
    last_edited = models.DateTimeField(auto_now=True)

    creator = models.ForeignKey(User, related_name="news_creator")
    last_editor = models.ForeignKey(User, related_name="news_last_editor")    

    objects = models.Manager() 
    active_objects = NewsManager()

    class Meta:
        verbose_name = verbose_name_plural = "News"
        ordering = ('-created',)
        get_latest_by = 'created'

    def save(self):
        """
        render markup to html before saving
        """
        
        self.raw_content = markup.render(self.content, self.markup)
        if self.active and not self.created:
            post_publish = bool(self.id)
            self.created = datetime.datetime.now()
            super(News, self).save()
            if post_publish:
                models.signals.post_save.send(sender=self.__class__, 
                                              instance=self, created=True)
        else: 
            super(News, self).save()
        
    @models.permalink
    def get_absolute_url(self):
        return ("news_detail", [self.slug])

    def __unicode__(self):
        return self.title



